<?php


namespace api\zmt\controller;


use api\zmt\model\OrderModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class OrderController extends RestBaseController
{


    //获取商品信息
    public function getGoodsList(){
        //获取搜索字段
        $name = input('name');
        $page = input('page/d',1);
        $listRow = input('list_row/d',10);
        //查询商品
        $goods = Db::name('goods')
            ->with('navigation')
            ->order(['id' => 'DESC'])
            ->field('id,name,image,booklet,status,gid')
            ->where('name','like','%'.$name.'%')
            ->page($page,$listRow)
            ->select();
        $this->success('商品列表',$goods);
    }
    //商品详情
    public function info(){
//        $arr=[
//            '颜色' => ['红色', '黑色','白色'],
//            '尺码' => ['M', 'L','XL'],
//        ];
//        halt(json_encode($arr, JSON_UNESCAPED_UNICODE));
        $id = input('id/d');
        if(!$id){
            $this->error('商品不存在');
        }
        $goods = Db::name('goods')->field('id,goods_list')->find($id);
        $goods['goods_list'] = json_decode($goods['goods_list']);
        $this->success('商品详情',$goods);
    }

    public function order(Request $request){
        $data = $request->post();
//        $info=[
//            ['颜色'=>'黑色','尺码'=>'M','价格'=>'10'],
//            ['颜色'=>'红色','尺码'=>'L','价格'=>'15']
//        ];
//        halt(json_encode($info,JSON_UNESCAPED_UNICODE));
        //查询商品
        $goods = Db::name('goods')
            ->where('id',$data['goods_id'])
            ->find();
        $list = $this->getGoodsInfo2($goods, $data['goods_info']);
        if(!$goods){
            $this->error('该商品不存在');
        }
        if($goods['status'] != 1){
            $this->error('该商品缺货或已下架');
        }
        $address = Db::name('delivery')->where('id',$data['address_id'])->find();
        if(!$address){
            $this->error('地址不存在');
        }
        $insert_data = [
            'user_id' => $request->id,
            'goods_name' => $goods['name'],
            'goods_info' => json_encode($data['goods_info']),
            'price' => $list['价格'],
            'num' => $data['num'],
            'total_price' => round($goods['money'] * $data['num'], 2),
            'trade_no' => date('YmdHis').mt_rand(1111,9999),
            'user_name' => $address['consignee'],
            'user_tel' => $address['mobile'],
            'user_address' => $address['area'].$address['address'],
            //'pay_type' => $data['pay_type'],
            'status' => 0,
            'remarks' => $data['remarks'],
            'create_time' => date('Y-m-d H:i:s'),
        ];
        $model = new OrderModel();
        $create = $model->save($insert_data);
        if ($create) {
            $this->success('订单创建成功', [
                'payInfo'=>[
                    'order_id' => $model->id
                ]
            ]);
        } else {
            return json(['code' => '0', 'message' => '订单创建失败']);
        }

    }

    protected function getGoodsInfo($goods,$spe)
    {
        $goodsSpe = json_decode($goods['info'], true);
        // halt($spe);
        foreach ($goodsSpe as $value) {
            if ($value['颜色'] == $spe['颜色'] && $value['尺码'] == $spe['尺码']) {
                return $value;
            }
        }
    }

    private function getGoodsInfo2($goods,$buy)
    {
        $goodsSku = json_decode($goods['info'],true);
        //循环的商品的规格
        foreach($goodsSku as $sku){
            $hasSku = true;
            //购买的规格
            foreach ($buy as $attr => $val) {
                if($sku[$attr] != $val) {
                    $hasSku = false;
                }
            }
            if ($hasSku) {
                return $sku;
            }else {
                continue;
            }
        }
    }

    public function wuliu()
    {
        $url = 'https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';
        $RequestData = [
            'LogisticCode' => '777221640641694'
        ];
        $apiKey = 'f2568315-f3c8-4057-af59-fd9573fde192';
        $RequestDataJson = json_encode($RequestData);
        $DataSign = urlencode(base64_encode(md5($RequestDataJson.$apiKey)));

        //其他参数
        $param = [
            'RequestData' => $RequestDataJson,
            'RequestType' => 8002,
            'EBusinessID' => 1855242,
            'DataSign' => $DataSign,
            'DataType' => 2
        ];
        $res = $this->curlRequest('POST',$url,'form',$param);
        $this->success('查询成功',$res);


    }

    // CURL
    function curlRequest($type, $url, $contentType, $data = [], $timeout = 60)
    {
        try {
            $type = strtoupper($type);
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url); // 设置请求链接
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 不直接输出页面
            curl_setopt($curl, CURLOPT_HEADER, 0); // 获取响应头向下
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);   // 请求超时时间，单位：秒
            curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1');
            if (substr($url, 0, 5) == 'https') {
                // 自动判断是否是 https 提交
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                // https请求，不验证证书和 hosts
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            }
            // 判断 Content-Type 类型
            if ($contentType == 'json') {
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
            }
            if ($contentType == 'form') {
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
            }
            switch ($type) {
                case "GET" :
                    curl_setopt($curl, CURLOPT_HTTPGET, true);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                    break;
                case "POST":
                    curl_setopt($curl, CURLOPT_POST, true);
                    if ($contentType == 'json') {
                        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                    }
                    if ($contentType == 'form') {
                        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                    }
                    break;
            }
            $result = curl_exec($curl);
            $err_code = curl_errno($curl);
            $curlInfo = curl_getinfo($curl);
            curl_close($curl);
            if ($err_code) {
                return ['status' => 'error', 'msg' => 'sendRequestError:' . $err_code];
            }
            if ($curlInfo['http_code'] == 200) {
                return json_decode($result, true);
            }
            return false;
        } catch (\Exception $e) {
            return ['status' => 'error', 'msg' => $e->getMessage()];
        }
    }
}